
package com.xbxkj.commen.controller;

import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.setting.Setting;
import com.aliyun.oss.OSSClient;
import com.xbxkj.commen.controller.helper.$;
import com.xbxkj.commen.controller.model.ApiResultModel;
import com.xbxkj.commen.service.*;
import com.xbxkj.commen.serviceImpl.OssServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.HostUnauthorizedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.Jedis;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 * @author Zhang
 * @date 2018-11-08
 */
@Slf4j
public abstract class BaseController   {
    @Autowired
  protected   UserService userService;

    @Autowired
  protected UserAddressService userAddressService;
    @Autowired
    protected RolePermissionService rolePermissionService;

    @Autowired
    protected AdminUserRoleService adminUserRoleService;

    @Autowired
    protected AdminUserService adminUserService;
    @Autowired
    protected AdminRoleService adminRoleService;

    @Autowired
    protected AdminPermissionService adminPermissionService;

    @Autowired
    protected DictionariesService dictionariesService;
    @Autowired
    protected ShopExamineService shopExamineService;
    @Autowired
    protected OssService ossService ;

    @Autowired
    protected ShopShopsService  shopShopsService;


    @Value("${aliyun.oss.endpoint}")
    protected String endPoint="";

    @Value("${redisDS.group:dev}")
    String redisGroup="";
   private final String jedisNullError="未配置redis，请先在根目录下/config文件夹创建配置文件/redis.setting";
    /**
     * 获取jedis
     *
     * @return
     */
    private Jedis jedis() {

        Setting setting=null;
        try {
              setting=new Setting(System.getProperty("user.dir")+"/config/redis.setting");
            log.info("当前redis环境为{}", redisGroup);
        }catch (Exception e){
            log.info(jedisNullError);
            return null;
        }
        return new RedisDS(setting,redisGroup).getJedis();
    }
    /**
     * 获取字符串缓存
     * @return
     */
    protected String getJSONCache(String key){
        Jedis jedis=jedis();
        String value=null;
        if(jedis==null){
            log.info(jedisNullError);
        }else{
            value= jedis.get(key);
            jedis.close();
        }

        return value;
    }
    /**
     * 缓存存储
     * @return
     */
    protected void putCache(String key, String jsonValue ){
        Jedis jedis=jedis();
        if(jedis==null){
            log.info(jedisNullError);
        }else{
           jedis.set(key,jsonValue);
            jedis.close();
        }
    }

    /**
     * 缓存存储  过期时间秒
     * @return
     */
    protected void putCache(String key  , String jsonValue , int time){
        Jedis jedis=jedis();
        if(jedis==null){
            log.info(jedisNullError);
        }else{
            jedis.set(key,jsonValue);
            jedis.expire(key,time);
            jedis.close();
        }
    }



    /**
     * 获取当前请求
     *
     * @return request
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    protected HttpSession getSession() {
        return getRequest().getSession();
    }
    /**
     * 获取当前请求
     *
     * @return response
     */
    protected HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
    /**
     * 方法名称: renderText<br>
     * 描述：返回普通文本浏览器
     */
    protected void renderText(String text){
        render(text, MediaType.TEXT_HTML_VALUE);
    }

    /**
     * 方法名称: renderJson<br>
     * 描述：返回JSON格式数据
     */
    protected void renderJson(String text){
        render(text,  MediaType.APPLICATION_JSON_UTF8_VALUE );
    }

    /**
     * 获取cookie
     * @param cookieName
     * @return
     */
    protected String getCookie(String cookieName) {
        Cookie[] cookies = getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }

        return null;
    }

    /**
     * 设置 cookie
     *
     * @param cookieName
     * @param value
     * @param age
     */
    protected void setCookie(String cookieName, String value, int age) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setMaxAge(age);
        getResponse().addCookie(cookie);
    }


    private void render(String text, String contentType){
        HttpServletResponse response;
        try{

            response = getResponse();
                response.setContentType(contentType);

            response.getWriter().write(text);
            response.getWriter().flush();
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * request内参数 转map
     * @return
     */
    protected    Map<String, Object> convertDataMap( ) {
        Map<String, String[]> properties = getRequest().getParameterMap();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Iterator<?> entries = properties.entrySet().iterator();
        Map.Entry<?, ?> entry;
        String name = "";
        String value = "";
        while (entries.hasNext())
        {
            entry = (Map.Entry<?, ?>) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj)
            {
                value = "";
            }
            else if (valueObj instanceof String[])
            {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++)
                {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            }
            else
            {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }
    /**
     * 对象转数组
     * @param obj
     * @return
     */
    protected static byte[] objectToByteArray (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 数组转对象
     * @param bytes
     * @return
     */
    protected static Object byteArrToObject (byte[] bytes) {
        Object object = null;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);// 创建ByteArrayInputStream对象
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);// 创建ObjectInputStream对象
            object = objectInputStream.readObject();// 从objectInputStream流中读取一个对象
            byteArrayInputStream.close();// 关闭输入流
            objectInputStream.close();// 关闭输入流
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;// 返回对象
    }


}